<template>
  <view class="container">
    <view class="titleBar">
      <text data-sts="0" :class="sts == 0 ? 'on' : ''" @tap="onStsTap">全部</text>
      <text data-sts="1" :class="sts == 1 ? 'on' : ''" @tap="onStsTap">待付款</text>
      <text data-sts="2" :class="sts == 2 ? 'on' : ''" @tap="onStsTap">待发货</text>
      <text data-sts="3" :class="sts == 3 ? 'on' : ''" @tap="onStsTap">待收货</text>
      <text data-sts="5" :class="sts == 5 ? 'on' : ''" @tap="onStsTap">已完成</text>
    </view>
    <!--  -->
    <view class="list">
      <view v-if="list.length == 0" class="empty">暂无数据</view>
      <!-- 订单列表 -->
      <block v-for="(item, index) in list" :key="index">
        <view class="item">
          <view class="statusInfo">
            <text>订单编号：{{ item.orderNumber }}</text>
            <view class="status">
              <text :class="'text ' + (item.status == 1 ? 'red' : '') + '  ' + (item.status == 5 || item.status == 6 ? 'gray' : '')">
                {{ item.status == 1 ? '待付款' : item.status == 2 ? '待发货' : item.status == 3 ? '待收货' : item.status == 5 ? '已完成' : '已取消' }}
              </text>

              <view v-if="item.status == 5 || item.status == 6" class="btnClear">
                <image class="clear-list-btn" src="@/static/images/icon/clear-his.png" :data-ordernum="item.orderNumber" @tap="delOrderList" />
              </view>
            </view>
          </view>

          <!-- 商品列表 -->
          <!-- 一个订单单个商品的显示 -->
          <block v-if="item.orderItemDtos.length == 1">
            <block v-for="(prod, index2) in item.orderItemDtos" :key="index2">
              <view>
                <view class="productInfo" :data-ordernum="item.orderNumber" @tap="onOrderInfo">
                  <view class="prod-pic">
                    <image :src="prod.pic" />
                  </view>
                  <view class="product">
                    <view class="name">{{ prod.prodName }}</view>
                    <view class="sku">{{ prod.skuName }}</view>
                    <view class="priceInfo">
                      <text class="price">
                        <text class="symbol">￥</text>
                        <text class="big-num">{{ wxs.parsePrice(prod.price)[0] }}</text>
                        <text class="small-num">.{{ wxs.parsePrice(prod.price)[1] }}</text>
                      </text>
                      <text class="count">x{{ prod.prodCount }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </block>
          </block>
          <!-- 一个订单多个商品时的显示 -->
          <block v-else>
            <view class="productInfo" :data-ordernum="item.orderNumber" @tap="onOrderInfo">
              <scroll-view scroll-x="true" scroll-left="0" scroll-with-animation="false" class="categories">
                <block v-for="(prod, index2) in item.orderItemDtos" :key="index2">
                  <view class="prod-pic">
                    <image :src="prod.pic" />
                  </view>
                </block>
              </scroll-view>
            </view>
          </block>

          <view class="countInfo">
            <text class="prodcount">{{ item.orderItemDtos ? item.orderItemDtos.length : '1' }}件商品</text>
            <view class="prodprice">
              合计：
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(item.actualTotal)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(item.actualTotal)[1] }}</text>
            </view>
          </view>
          <!--   -->
          <view class="footer">
            <view class="btn">
              <text v-if="item.status == 1" class="button" :data-ordernum="item.orderNumber" hover-class="none" @tap="onCancelOrder">取消订单</text>
              <text v-if="item.status == 1" class="button warn" :data-ordernum="item.orderNumber" hover-class="none" @tap="onPrepay(item)">付款</text>
              <text v-if="item.status == 3 || item.status == 5" class="button" :data-ordernum="item.orderNumber" hover-class="none" @tap="toDeliveryPage">查看物流</text>
              <text v-if="item.status == 3" class="button warn" :data-ordernum="item.orderNumber" hover-class="none" @tap="onConfirmReceive">确认收货</text>
              <text v-if="item.status == 5" class="button warn" :data-ordernum="item.orderNumber" hover-class="none" @tap="onComment">评论</text>
            </view>
          </view>
        </view>
      </block>
    </view>
  </view>
</template>

<script setup>
const wxs = number();

const sts = ref(0);
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  if (options.sts) {
    sts.value = options.sts;
    loadOrderData(options.sts, 1);
  } else {
    loadOrderData(0, 1);
  }
});

const current = ref(1);
const pages = ref(0);
/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom(() => {
  if (current.value < pages.value) {
    loadOrderData(sts.value, current.value + 1);
  }
});

const list = ref([]);
/**
 * 加载订单数据
 */
const loadOrderData = (sts, currentParam) => {
  uni.showLoading(); // 加载订单列表
  http
    .request({
      url: '/p/myOrder/myOrder',
      method: 'GET',
      data: {
        current: currentParam,
        size: 10,
        status: sts
      }
    })
    .then(({ data }) => {
      let listParam = [];
      if (data.current === 1) {
        listParam = data.records;
      } else {
        listParam = list.value;
        Array.prototype.push.apply(listParam, data.records);
      }
      list.value = listParam;
      pages.value = data.pages;
      current.value = data.current;
      uni.hideLoading();
    });
};

/**
 * 状态点击事件
 */
const onStsTap = (e) => {
  sts.value = e.currentTarget.dataset.sts;
  loadOrderData(sts.value, 1);
};

/**
 * 查看物流
 */
const toDeliveryPage = (e) => {
  uni.navigateTo({
    url: '/pages/user/delivery/delivery?orderNum=' + e.currentTarget.dataset.ordernum
  });
};

/**
 * 取消订单
 */
const onCancelOrder = (e) => {
  const ordernum = e.currentTarget.dataset.ordernum;
  uni.showModal({
    title: '',
    content: '确定取消订单？',
    confirmColor: '#e02e2e',
    cancelColor: '#666',
    cancelText: '取消',
    confirmText: '确定',

    success(res) {
      if (res.confirm) {
        uni.showLoading({
          mask: true
        });
        http
          .request({
            url: '/p/myOrder/cancel/' + ordernum,
            method: 'PUT',
            data: {}
          })
          .then(() => {
            loadOrderData(sts.value, 1);
            uni.hideLoading();
          });
      }
    }
  });
};

const onPrepay = (item) => {
  let orderNo = item.orderNumber;
  let productName = item.orderItemDtos[0].prodName;
  let amount = item.actualTotal;
  http
    .request({
      url: '/p/pay/prepay',
      method: 'POST',
      data: {
        orderNumbers: orderNo,
        body: productName,
        amount: amount,
        openid: uni.getStorageSync('openId')
      }
    })
    .then(({ data }) => {
      onWechatPayment(data);
    })
    .finally(() => {});
};

const onWechatPayment = (params) => {
  // let res = {
  //   appId: 'wx1f910fb2bad5f6d9',
  //   nonceStr: 'MbASefslFBRdZZDFlAlUYdwOaHzLDvPu',
  //   packageVal: 'prepay_id=wx21180011081346a9da2f2145997f630000',
  //   signType: 'RSA',
  //   paySign:
  //     'SpVDtMkb+sU8nqxacTiiaA1MtBpDwif7hCXCTp7r+Dm6RAHk/NuJu+HD47Ty/QzZp64BAgcmJNDmUkuauE+tTjSWOYpKe1a1DYCJbCmhC46ME0L3DP3yYs9I+yZ++9EKGX1FpEZYPMSVHIOnqUEMFmEIYdnR/NHbBaYqz8J+j/QXFuzBBIkOZVECT6CoKiMxrZZOyItO5uGThlP9guWzKn+7uIvJ+NLZe/SBEarr/GcLAYB+ObzO+Gvhe+fJG4kuC/lQMIRnXux5FRZfiT26WOrKaGXwqyOawpBj79u6JzU3h0x6/tDrSnn3EWvuTKo7mM1xi4CkqptqkZT1/A6jqg==',
  //   timeStamp: '1729504810'
  // };
  if (!params.appId) {
    uni.showToast({
      title: '支付失败，请联系客服0',
      icon: 'none'
    });
    return;
  }
  // 拉起支付
  uni.requestPayment({
    provider: 'wxpay',
    timeStamp: params.timeStamp,
    nonceStr: params.nonceStr,
    package: params.packageVal,
    signType: params.signType,
    paySign: params.paySign,
    success: (res) => {
      console.error('微信支付结果：', res);
      if (res.errMsg == 'requestPayment:ok') {
        uni.showToast({
          title: '支付成功',
          success() {
            setTimeout(function () {
              uni.reLaunch({
                url: '/pages/index/paySuccess/paySuccess?type=1&processId=' + params.processId /* + '&orderId=' + that.orderAmountObj.orderId */
              });
            }, 1500);
          }
        });
      } else {
        // that.$refs.authPop.open();
        uni.showToast({
          title: '支付失败1：' + res.errMsg,
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      // that.$refs.authPop.open();
      console.log('微信支付失败：', err);
      uni.showToast({
        title: '支付失败，请联系客服2',
        icon: 'none'
      });
    }
  });
};

/**
 * 模拟支付，直接提交成功
 * @param e
 */
const normalPay = (e) => {
  uni.showLoading({
    mask: true
  });
  http
    .request({
      url: '/p/order/normalPay',
      method: 'POST',
      data: {
        orderNumbers: e.currentTarget.dataset.ordernum
      }
    })
    .then(({ data }) => {
      uni.hideLoading();
      if (data) {
        uni.showToast({
          title: '模拟支付成功',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/index/payResult/payResult?sts=1&orderNumbers=' + e.currentTarget.dataset.ordernum
          });
        }, 1200);
      } else {
        uni.showToast({
          title: '支付失败！',
          icon: 'none'
        });
      }
    });
};

/**
 * 查看订单详情
 */
const onOrderInfo = (e) => {
  uni.navigateTo({
    url: '/pages/user/orderInfo/orderInfo?orderNum=' + e.currentTarget.dataset.ordernum
  });
};

//评论
const onComment = (e) => {
  uni.showToast({
    title: '评论',
    icon: 'none'
  });
};

/**
 * 确认收货
 */
const onConfirmReceive = (e) => {
  uni.showModal({
    title: '',
    content: '确定收货？',
    confirmColor: '#e02e2e',
    success(res) {
      if (res.confirm) {
        uni.showLoading({
          mask: true
        });
        http
          .request({
            url: '/p/myOrder/receipt/' + e.currentTarget.dataset.ordernum,
            method: 'PUT'
          })
          .then(() => {
            loadOrderData(sts.value, 1);
            uni.hideLoading();
          });
      }
    }
  });
};

/**
 * 删除已完成||已取消的订单
 * @param e
 */
const delOrderList = (e) => {
  uni.showModal({
    title: '',
    content: '确定删除此订单？',
    confirmColor: '#e02e2e',

    success(res) {
      if (res.confirm) {
        const ordernum = e.currentTarget.dataset.ordernum;
        uni.showLoading();

        http
          .request({
            url: '/p/myOrder/' + ordernum,
            method: 'DELETE'
          })
          .then(() => {
            loadOrderData(sts.value, 1);
            uni.hideLoading();
          });
      }
    }
  });
};
</script>

<style scoped lang="scss">
@import './orderList.scss';
</style>
